package com.beiben.trialproduce.part.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.beiben.common.GlobalConstant;
import com.beiben.experiment.repair.domain.Repair;
import com.beiben.experiment.repair.service.IRepairService;
import com.beiben.system.file.domain.File;
import com.beiben.system.user.domain.BeiBenUser;
import com.beiben.trialproduce.part.domain.PartExcelVo;
import com.beiben.trialproduce.samplecar.domain.SampleCar;
import com.beiben.trialproduce.samplecar.domain.SampleCarExcelVo;
import com.beiben.utils.excel.ExcelStyleAnnotationCellWriteHandler;
import com.beiben.utils.excel.ExcelUtils;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.beiben.trialproduce.part.mapper.PartMapper;
import com.beiben.trialproduce.part.domain.Part;
import com.beiben.trialproduce.part.service.IPartService;

/**
 * 零件Service业务层处理
 * 
 * @author 熊国强
 * @date 2020-11-25
 */
@Service
public class PartServiceImpl implements IPartService 
{

    private static final Logger log = LoggerFactory.getLogger(PartServiceImpl.class);


    @Autowired
    private PartMapper partMapper;

    @Autowired
    private IRepairService repairService;

    /**
     * 查询零件
     * 
     * @param partId 零件ID
     * @return 零件
     */
    @Override
    public Part selectPartById(Long partId)
    {
        return partMapper.selectPartById(partId);
    }

    /**
     * 查询零件列表
     * 
     * @param part 零件
     * @return 零件
     */
    @Override
    public List<Part> selectPartList(Part part)
    {
        return partMapper.selectPartList(part);
    }

    /**
     * 新增零件
     * 
     * @param part 零件
     * @return 结果
     */
    @Override
    public int insertPart(Part part)
    {
        return partMapper.insertPart(part);
    }

    /**
     * 修改零件
     * 
     * @param part 零件
     * @return 结果
     */
    @Override
    public int updatePart(Part part)
    {
        return partMapper.updatePart(part);
    }

    /**
     * 批量删除零件
     * 
     * @param partIds 需要删除的零件ID
     * @return 结果
     */
    @Override
    public int deletePartByIds(Long[] partIds)
    {
        return partMapper.deletePartByIds(partIds);
    }

    /**
     * 删除零件信息
     * 
     * @param partId 零件ID
     * @return 结果
     */
    @Override
    public int deletePartById(Long partId)
    {
        return partMapper.deletePartById(partId);
    }

    /**
     * 导入数据
     *
     * @param list 数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param
     * @return 结果
     */
    @Override
    public String importPart(List<Part> list, Boolean isUpdateSupport) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Part part : list)
        {
            try
            {
                this.insertPart(part);
                successNum++;
                successMsg.append("<br/>" + successNum + "、零件号： " + part.getCode() + " 导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、零件号: " + part.getCode()  + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共: " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共: " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 导出零件列表
     *
     * @param part 零件
     * @return 零件集合
     */
    @Override
    public AjaxResult downLoadPartExcel(Part part) {
        String fileName = ExcelUtils.encodingFilename("科研验证物资库存汇总表");
        List<PartExcelVo> list = partMapper.selectPartExcelList(part);
        int i =0;
        for(PartExcelVo pt : list ){
            i++;
           String partNum =  String.valueOf(pt.getPartNum());
            pt.setNormalStock("√");
            pt.setUnNormalSubtotal(partNum);
            pt.setStockYearSubtotal(partNum);
            pt.setOrderNum(String.valueOf(i));
            if(null!=pt.getProductionTime()){
                Long poorDay = com.beiben.utils.DateUtil.getDatePoorDay(new Date(),pt.getProductionTime());
                if(poorDay<365){
                    pt.setOneYear("√");
                }else if(poorDay>=365&&poorDay<=2*365){
                    pt.setOneTwoYear("√");
                }else if(poorDay>2*365&&poorDay<=3*365){
                    pt.setTwoThreeYear("√");
                }else if(poorDay>3*365&&poorDay<=5*365){
                    pt.setThreeFiveYear("√");
                }else if(poorDay>5*365){
                    pt.setFiveYear("√");
                }
            }
        }
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        EasyExcel.write(ExcelUtils.getAbsoluteFile(fileName), PartExcelVo.class).registerWriteHandler(myHorizontalCellStyleStrategy()).registerWriteHandler(myAnnotHoriCellStyleStrategy()).sheet("零件")
                .doWrite(list);
        return AjaxResult.success(fileName);
    }

    /**
     * 修改零部件状态
     *
     * @param part 维修详情
     * @return 结果
     */
    @Override
    public int updatePartState(Part part) {
        return  partMapper.updatePartState(part.getPartIds(),part.getPartState(),part.getPartUseState());
    }


    private HorizontalCellStyleStrategy myAnnotHoriCellStyleStrategy(){
        return  new ExcelStyleAnnotationCellWriteHandler(PartExcelVo.class,
                new WriteCellStyle(), new WriteCellStyle());
    }


    private HorizontalCellStyleStrategy myHorizontalCellStyleStrategy(){
        //表头样式策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置表头居中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //表头前景设置白色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setBold(true);
        headWriteFont.setFontName("宋体");
        headWriteFont.setFontHeightInPoints((short)9);
        headWriteCellStyle.setWriteFont(headWriteFont);
        //内容样式策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        WriteFont contentWriteFont = new WriteFont();
        //内容字体大小
        contentWriteFont.setFontName("宋体");
        contentWriteFont.setFontHeightInPoints((short)9);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        //设置自动换行
        contentWriteCellStyle.setWrapped(true);
        //设置垂直居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //设置水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //设置边框样式
        setBorderStyle(contentWriteCellStyle);
        //内容风格可以定义多个。
        List<WriteCellStyle>   listCntWritCellSty =  new ArrayList<>();
        listCntWritCellSty.add(contentWriteCellStyle);
//        WriteCellStyle contentWriteCellStyle2 = new WriteCellStyle();
//        // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色。
//        // 头默认了 FillPatternType所以可以不指定。
//        contentWriteCellStyle2.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
//        // 背景绿色
//        contentWriteCellStyle2.setFillForegroundColor(IndexedColors.WHITE.getIndex());
//        //设置垂直居中
//        contentWriteCellStyle2.setVerticalAlignment(VerticalAlignment.CENTER);
//        //设置水平居中
//        contentWriteCellStyle2.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //设置边框样式
//        setBorderStyle(contentWriteCellStyle2);
//        listCntWritCellSty.add(contentWriteCellStyle2);
        // 水平单元格风格综合策略(表头 + 内容)
        return  new HorizontalCellStyleStrategy(headWriteCellStyle, listCntWritCellSty);
    }

    private void setBorderStyle(WriteCellStyle contentWriteCellStyle){
        //设置边框样式
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        // contentWriteCellStyle.setBottomBorderColor(IndexedColors.BLUE.getIndex()); //颜色
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
    }
}
